﻿#define _CRT_SECURE_NO_WARNINGS
#include "seqlist.h"

//顺序表的初始化
void slinit(sl* ps)
{
	ps->arr = NULL;
	ps->capacity = 0;
	ps->size = 0;
}
//空间的扩容
void capacitycheck(sl* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity = 0 ? 5 : 2 * ps->capacity;
		seqdatatype * temp = (seqdatatype*)realloc(ps->arr, newcapacity * sizeof(seqdatatype));
		if (temp == NULL)
		{
			perror("realloc err!");
			temp = NULL;
		}
		ps->arr = temp;
		ps->capacity = newcapacity;
	}
}

void slpushback(sl* ps, seqdatatype x)//尾插
{
	assert(ps);
	capacitycheck(ps);//判断是否需要扩容
	ps->arr[ps->size] = x;
	ps->size++;
}

//头插
void slfrontback(sl* ps, seqdatatype x)
{
	assert(ps);
	capacitycheck(ps);//判断是否需要扩容
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	++ ps->size;
}

void slpopback(sl* ps)//尾删
{
	assert(ps && ps->size);
	-- ps->size;
}

void slpopfront(sl* ps)//头删
{
	assert(ps && ps->size);
	for (int i = 1; i < ps->size; i++)
	{
		ps->arr[i - 1] = ps->arr[i];
	}
	--ps->size;
}

//查找
//找到了，返回下标；未找到，返回-1
int slfrind(sl* ps, seqdatatype x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}

//指定位置之前插⼊数据
void slinsert(sl* ps, int pos, seqdatatype x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	capacitycheck(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	++ps->size;
}

//指定位置删除数据
void slerase(sl* ps, int pos)
{
	assert(ps && ps->size);
	assert(pos >= 0 && pos < ps->size);

	for (int i = pos; i <ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i+1];
	}
	--ps->size;
}

//销毁
void sldestroy(sl* ps) 
{
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}